package com.sz.app.oss.api.system;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.app.oss.exception.ErrorCodes;
import com.sz.biz.app.web.BaseController;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.dto.TreeNode;
import com.sz.common.base.exception.BizException;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.core.system.dto.OrgDto;
import com.sz.common.core.system.service.OrgService;
import com.sz.app.oss.api.system.dto.OrgNodeDragDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

/**
 * Function: OrgController <br>
 * Author: wentao.chang <br>
 * Date: 2016-10-31 10:04:00
 */
@RestController
@RequestMapping("${api}/sys/orgs")
@Api(description = " ", tags = "002_1、组织管理")
public class OrgController extends BaseController {
    @Autowired
    private OrgService orgsService;

    /**
     * 按Id查询一个组织
     *
     * @throws BizException   bizex
     * @throws ParseException parseex
     */
    @ApiOperation(value = "根据id获取组织", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "组织的id ",
                    required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/{orgid}", method = {RequestMethod.GET})
    public ResultDto findById(@PathVariable("orgid") int orgid) throws BizException, ParseException {
        OrgDto org = orgsService.findById(1, orgid);
        ResultDto dto = new ResultDto();
        dto.setData(org);
        return dto;
    }

    /**
     * 给某个用户组新建一个组织
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "新建一个组织", notes = "-<br>权限：" + Permissions.SYS_MGT_ORG)
    @ApiImplicitParams({@ApiImplicitParam(name = "orgDto", value = "需要的参数：parentId,name\r\n"
            + "shortName,code,description", required = true, paramType = "OrgDto")})
    @RequestMapping(value = "", method = {RequestMethod.POST})
    @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto saveOrg(@RequestBody OrgDto orgDto) throws Exception {
        int orgId = orgsService.saveOrg(1, orgDto);
        ResultDto dto = getSaveSuccessDto(MessagesCodes.MODULE_ORG);
        dto.setData(orgId);
        return dto;
    }

    /**
     * 修改一个组织
     *
     * @throws Exception ex
     */
    @ApiOperation(value = "修改一个组织", notes = "-<br>权限：" + Permissions.SYS_MGT_ORG)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "组织的id ",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "orgDto", value = "需要的参数：name,shortName,\r\n"
                    + "code,description,parentId",
                    required = true, paramType = "com.sz.common.core.system.dto.OrgDto")})
    @RequestMapping(value = "/{orgid}", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto updateOrg(@PathVariable int orgid, @RequestBody OrgDto orgDto) throws Exception {
        orgsService.updateOrg(1, orgid, orgDto);
        ResultDto dto = getUpdateSuccessDto(MessagesCodes.MODULE_ORG);
        dto.setData(orgid);
        return dto;
    }

    /**
     * 获取指定组织机构的树 可指定关键字查询
     *
     * @throws BizException   bizex
     * @throws ParseException parseex
     */
    @ApiOperation(value = "获取指定组织机构的树 可指定关键字查询", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "组织查询关键字 默认空", dataType = "string", paramType = "query")})
    @RequestMapping(value = "/tree", method = {RequestMethod.GET})
    //@RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto getOrgTreeByOrgGroupid(@RequestParam(required = false, defaultValue = "") String q)
            throws BizException, ParseException {
        List<TreeNode> orgs = orgsService.getOrgTreeByOrgGroupId(1, q);
        ResultDto dto = new ResultDto();
        dto.setData(orgs);
        return dto;
    }

    /**
     * 获取指定组织机构的列表 可指定关键字查询
     *
     * @throws BizException   bizex
     * @throws ParseException parseex
     */
    @ApiOperation(value = "获取指定组织机构的列表 可指定关键字查询", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "组织查询关键字 默认空", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "porgid", value = "父组织的id 在此父组织下查询  默认0 查询所有",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "", method = {RequestMethod.GET})
    // @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto getOrgListByOrgGroupid(@RequestParam(required = false, defaultValue = "") String q,
                                            @RequestParam(required = false, defaultValue = "0") int porgid)
            throws BizException, ParseException {
        List<OrgDto> orgs = orgsService.getOrgListByOrgGroupId(1, q, porgid);
        ResultDto dto = new ResultDto();
        dto.setData(orgs);
        return dto;
    }

    /**
     * 获取指定级别的子节点
     *
     * @throws BizException   bizex
     * @throws ParseException parseex
     */
    @ApiOperation(value = "获取指定级别的子节点", notes = "-")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentid", value = "组织的父节点id,加载根节点parentid为0",
                    required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/subnode/{parentid}", method = {RequestMethod.GET})
    public ResultDto getOrgSubNodeByParentId(@PathVariable int parentid)
            throws BizException, ParseException {
        List<TreeNode> orgs = orgsService.getSubOrgDtos(1, parentid);
        ResultDto dto = new ResultDto();
        dto.setData(orgs);
        return dto;
    }

    /**
     * 拖动组织
     *
     * @throws BizException   bizex
     * @throws ParseException parseex
     */
    @ApiOperation(value = "拖动组织", notes = "-<br>权限：" + Permissions.SYS_MGT_ORG)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "拖动组织的id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "dto", value = "拖动对象{targetparentid,targetpreid}",
                    required = true, dataType = "OrgNodeDragDto", paramType = "body")})
    @RequestMapping(value = "/drag/{orgid}", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto dragOrgTreeNode(@PathVariable int orgid, @RequestBody OrgNodeDragDto dto)
            throws BizException, ParseException {
        if (dto.getTargetpreid() == null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_COMMON, "请检查组织！");
        }
        if (dto.getTargetparentid() == 0 && dto.getTargetpreid() == 0) {
            throw Exceptions.bizException(ErrorCodes.ERROR_COMMON, "请检查组织！");
        }
        orgsService.dragOrgTree(1, orgid, dto.getTargetparentid(), dto.getTargetpreid());
        ResultDto rdto = getOperateSuccessDto(MessagesCodes.ORG_DRAG_SUCCESS);
        rdto.setData(orgid);
        return rdto;
    }

    /**
     * 组织上移下移
     *
     * @throws BizException   bizex
     * @throws ParseException parseex
     */
    @ApiOperation(value = "组织上移下移", notes = "-<br>权限：" + Permissions.SYS_MGT_ORG)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "移动组织的id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "direct", value = "移动方向:-1向上移动 1向下移动",
                    required = true, dataType = "int", paramType = "query")})
    @RequestMapping(value = "/shift/{orgid}", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto shiftOrgTreeNode(@PathVariable int orgid, @RequestParam("direct") int direct)
            throws BizException, ParseException {
        if (Math.abs(direct) != 1) {
            throw Exceptions.bizException(ErrorCodes.ERROR_MODEL_ORG_SHIFT_DIRECT_ERR);
        }
        orgsService.shiftOrgTreeNode(1, orgid, direct);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.ORG_SHIFT_SUCCESS);
        dto.setData(orgid);
        return dto;
    }

    @ApiOperation(value = "组织删除", notes = "删除该组织后，该组织下所有子组织、用户、角色也被删除。<br>权限：" + Permissions.SYS_MGT_ORG)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "删除组织的id",
                    required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/{orgid}", method = {RequestMethod.DELETE})
    @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto deleteOrgTreeNode(@PathVariable int orgid)
            throws Exception {
        orgsService.deleteOrgTreeNode(1, orgid);
        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_ORG);
        dto.setData(orgid);
        return dto;
    }

    /**
     * 组织分配角色
     *
     * @throws BizException   bizex
     * @throws ParseException parseex
     */
    @ApiOperation(value = "组织分配角色", notes = "组织分配角色<br>权限：" + Permissions.SYS_MGT_ORG)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "分配组织的id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "roleIds", value = "角色的id列表字符串,用','分割",
                    required = true, dataType = "string", paramType = "body")})
    @RequestMapping(value = "/{orgid}/assignrole", method = {RequestMethod.PUT})
    @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto assignOrgRoles(@PathVariable int orgid, @RequestBody String roleIds)
            throws BizException, ParseException {
        orgsService.assignOrgRoles(1, orgid, roleIds);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.ORG_ASSIGN_ROLES_SUCCESS);
        dto.setData(orgid);
        return dto;
    }

    /**
     * 组织删除角色
     *
     * @throws BizException   bizex
     * @throws ParseException parseex
     */
    @ApiOperation(value = "组织删除角色", notes = "组织删除角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "删除组织的id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "roleId", value = "角色的id",
                    required = true, dataType = "int", paramType = "path")})
    @RequestMapping(value = "/{orgId}/removerole/{roleId}", method = {RequestMethod.DELETE})
    @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto removeOrgRoles(@PathVariable int orgId, @PathVariable int roleId)
            throws BizException, ParseException {
        orgsService.removeOrgRole(1, orgId, roleId);
        ResultDto dto = getOperateSuccessDto(MessagesCodes.ORG_REMOVE_ROLES_SUCCESS);
        dto.setData(orgId);
        return dto;
    }

    /**
     * 组织分配人
     *
     * @throws BizException   bizex
     * @throws ParseException parseex
     */
   /* @ApiOperation(value = "组织分配用户 增量", notes = "组织分配用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "组织的id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "userIds", value = "用户的id列表字符串,\r\n用','分割,增量更新,\r\n不删除已有用户",
                    required = true, dataType = "string", paramType = "body")})
    @RequestMapping(value = "/{orgid}/assignuser", method = {RequestMethod.PUT})
    public ResultDto assignOrgUserIds(@PathVariable int orgid, @RequestBody String userIds)
            throws BizException, ParseException {
        orgsService.assignOrgUsers(1, orgid, userIds);
        ResultDto dto = new ResultDto();
        dto.setData(orgid);
        dto.setMsg(getOperateSuccessMsg());
        return dto;
    }*/

    /**
     * 组织删除角色
     *
     * @throws BizException   bizex
     * @throws ParseException parseex
     */
   /* @ApiOperation(value = "组织删除用户", notes = "组织删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgid", value = "组织的id",
                    required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "userIds", value = "用户的id列表字符串,用','分割",
                    required = true, dataType = "string", paramType = "body")})
    @RequestMapping(value = "/{orgid}/removeuser", method = {RequestMethod.DELETE})
    @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto removeOrgUsers(@PathVariable int orgid, @RequestBody String userIds)
            throws BizException, ParseException {
        orgsService.removeOrgUsers(1, orgid, userIds);
        ResultDto dto = new ResultDto();
        dto.setData(orgid);
        dto.setMsg(getOperateSuccessMsg());
        return dto;
    }*/

    /**
     * 异步校验编码
     */
    @ApiOperation(value = "异步校验编码", notes = "异步校验编码<br>权限：" + Permissions.SYS_MGT_ORG)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "组织id 修改时传id 新增时传空",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/checkcode", method = {RequestMethod.GET})
    @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto orgCodeCheck(@RequestParam String code,
                                  @RequestParam(required = false, defaultValue = "0") int orgId) {
        orgsService.orgCodeCheck(1, orgId, code);
        return new ResultDto();
    }

    /**
     * 异步校验名称
     */
    @ApiOperation(value = "异步校验名称", notes = "异步校验名称<br>权限：" + Permissions.SYS_MGT_ORG)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "parentId",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "组织id 修改时传id 新增时传空",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/checkname", method = {RequestMethod.GET})
    @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto orgNameCheck(@RequestParam String name, @RequestParam int parentId,
                                  @RequestParam(required = false, defaultValue = "0") int orgId) {
        orgsService.orgNameCheck(1, parentId, orgId, name);
        return new ResultDto();
    }

    /**
     * 异步校验简称
     */
    @ApiOperation(value = "异步校验简称", notes = "异步校验简称<br>权限：" + Permissions.SYS_MGT_ORG)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shortName", value = "简称",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "parentId",
                    required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "组织id 修改时传id 新增时传空",
                    dataType = "int", paramType = "query")})
    @RequestMapping(value = "/checkshortname", method = {RequestMethod.GET})
    @RequiresPermissions(value = {Permissions.SYS_MGT_ORG})
    public ResultDto orgShortNameCheck(@RequestParam String shortName, @RequestParam int parentId,
                                       @RequestParam(required = false, defaultValue = "0") int orgId) {
        orgsService.orgShortNameCheck(1, parentId, orgId, shortName);
        return new ResultDto();
    }
}
